package com.fxz.common.exception;

import com.fxz.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


//定义全局控制器异常处理
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    //实体校验异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        ObjectError objectError = result.getAllErrors().stream().findFirst().get();
        log.info("实体校验异常异常:------{}",e.getMessage());
        return Result.fail(objectError.getDefaultMessage());
    }

    //返回的状态码
    //要处理异常的类型
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e){
        log.info("Assert异常:------{}",e.getMessage());
        return Result.fail(e.getMessage());
    }

    //返回的状态码
    //要处理异常的类型
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.info("运行时异常:------{}",e.getMessage());
        return Result.fail(e.getMessage());
    }
}
